<template>
  <div v-loading="pageLoading">
    <el-tabs v-if="currentNavCode" v-model="currentNavCode" :before-leave="handleBeforeleave">
      <el-tab-pane v-for="(item,index) in navs" :key="index" :label="item.name" :name="'nav_'+item.id">
        <div v-if="load && currentNavCode === 'nav_'+item.id">
          <component :is="item.app" v-if="item.app" />
          <common-page
            v-else
            ref="common"
            :ccode="item.id"
            isTabPage
          />
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-empty v-else :image-size="200" description="未配置子页面" />
  </div>
</template>
<script>
import {
  getNavByPageId
} from '@admin/api/common'
import {
  loadView
} from '@/utils/index'
export default {
  name: 'TabPage',
  provide() {
    return {
      tabPage: this
    }
  },
  data() {
    return {
      pageLoading: true,
      navs: [],
      currentNav: {},
      currentNavCode: '',
      load: true // 解决渲染问题
    }
  },
  computed: {
    code: function() {
      return this.$route.meta.code
    }
  },
  created: function() {
    this.createTab()
  },
  methods: {
    handleBeforeleave(activeName, oldActiveName) {
      this.load = false
      setTimeout(() => {
        this.load = true
      }, 100)
      return true
    },
    createTab() {
      const params = {
        pageId: this.code
      }
      getNavByPageId(params).then((res) => {
        this.navs = res.data.map(item => {
          if (item.vueComponent) {
            item.app = loadView(item.vueComponent)
          }
          return item
        }).sort((a,b)=>{
          return a.orderId >= b.orderId ? 1 : -1
        })
        this.setDefaultNav()
      }).finally(() => {
        this.pageLoading = false
      })
    },
    setDefaultNav() {
      if (this.navs.length > 0) {
        this.currentNav = this.navs[0]
        this.currentNavCode = 'nav_' + this.currentNav.id
      }
    },
    // 切换tab页时还原$CD变量
    restoreGlobal(){
      if(this.$refs.common && this.$refs.common.length){
        this.$refs.common[0].restoreGlobal()
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
